/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.openjawtech.xscraper.web.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author Wenbo.Sun
 */
public class TimeUtil {

    private static final Log log = LogFactory.getLog(TimeUtil.class);

    public static Date newDate(String str) {
        Date date = null;
        try {
            log.debug("create new date dd/MM/yyyy -- " + str);
            date = new SimpleDateFormat("dd/MM/yyyy").parse(str);
        } catch (ParseException ex) {
            log.error("create new date failed", ex);
            throw ex;
        } finally {
            return date;
        }
    }

    public static Date newDate(int year, int month, int date) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, date, 0, 0, 0);
        return calendar.getTime();
    }

    public static Calendar newCalendar(String str) {
        Calendar calendar = Calendar.getInstance();
        try {
            log.debug("create new calendar dd/MM/yyyy -- " + str);
            Date date = new SimpleDateFormat("dd/MM/yyyy").parse(str);
            calendar.setTime(date);
        } catch (ParseException ex) {
            log.error("create new calendar failed", ex);
            throw ex;
        } finally {
            return calendar;
        }
    }

    public static Calendar newCalendar(int year, int month, int date) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, date, 0, 0, 0);
        return calendar;
    }

    public static Calendar newCalendar(Date date) {
        Calendar calendar = Calendar.getInstance();
        log.debug("create new calendar -- " + date.toString());
        calendar.setTime(date);
        return calendar;

    }

    public static String dateFormat(Date date){
        return new SimpleDateFormat("dd/MM/yyyy").format(date);
    }

    public static Calendar preOrNextCalendar(Calendar cal, int days){
        int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
        cal.setTimeInMillis(cal.getTimeInMillis() + MILLIS_IN_DAY * days );
        return cal;
    }

}
